package class0815;

/**
 * @Author:galaxy_yan
 * @Date: 2022/8/16
 * @Time: 9:29
 * @Description
 * 二分查找：有序数组
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,9};
        System.out.println(binarySearch(arr,5));
    }
    public static int binarySearch(int[] arr,int key){
        int left=0;
        int right=arr.length-1;
        while(left<= right){
//            int mid=(left+right)/2;
//            int mid=(left+right)>>1;
//            >>优先级低于 + 一定要带（）
            int mid=left+((right-left)>>1);
            if(key==arr[mid]){
                return mid;
            }else if(key<arr[mid]){
                right=mid-1;
            }else {
                left=mid+1;
            }
        }
        return -1;
    }

    public static int binarySearch1(int[] arr,int key){
        int left=0;
        int right= arr.length;
        while(left<right){
            int mid=left+((right-left)>>1);
            if(key==arr[mid]){
                return mid;
            }else if(key<arr[mid]){
                right=mid;
            }else {
                left=mid+1;
            }
        }
        return -1;
    }
}
